<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;


class ChangeFunction extends Model
{


    // 表名
    protected $name = 'change_function';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text'
    ];


    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function changecategory()
    {
        return $this->belongsTo('ChangeCategory', 'change_category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public static function getStatusText($status)
    {
        $statusArr = [
            '0' => '开启',
            '1' => '关闭',
        ];
        return isset($statusArr[$status]) ? $statusArr[$status] : false;
    }

    /**
     * 列表
     * @param $postData
     * @return array
     */
    public static function getList($postData)
    {
        $where = '1=1';
        $order = 'a.id desc';
        $page = isset($postData['page']) && !empty($postData['page']) ? intval($postData['page']) : 1;
        $limit = isset($postData['limit']) && !empty($postData['limit']) ? intval($postData['limit']) : 10;
        $start = ($page - 1) * $limit;
        $field = "a.*";

        $list = db('change_function')
            ->alias('a')
            ->where($where)
            ->order($order)
            ->limit($start, $limit)
            ->field($field)
            ->select();
        if (!empty($list)) {
            foreach ($list as &$v) {
                $v['createtimeText'] = isset($v['createtime']) && !empty($v['createtime']) ? date('Y-m-d H:i:s', $v['createtime']) : '';
                $v['statusText'] = isset($v['status']) ? self::getStatusText($v['status']) : '';
                $v['documentStrArr'] = [];
                if (!empty($v['document_str'])) {
                    $v['documentStrArr'] = json_decode($v['document_str'], true);
                    foreach ($v['documentStrArr'] as &$v1) {
                        $v1['template'] = db('template')
                            ->where("id={$v1['id']}")
                            ->field('id, name, src')
                            ->find();
                    }
                    unset($v1);
                }
                $v['changeCategoryArr'] = [];
                if (!empty($v['change_category_ids'])) {
                    $v['changeCategoryArr'] = db('change_category')
                        ->where("id in ({$v['change_category_ids']})")
                        ->field('id, name, status')
                        ->select();
                }
            }
            unset($v);
        }

        $total = db('change_function')
            ->alias('a')
            ->where($where)
            ->count();

        return [
            'list' => $list,
            'total' => $total,
        ];

    }

    /**
     * 新增
     * @param $postData
     * @return bool
     */
    public static function addRow($postData)
    {
        $changeCategoryArr = explode(',', $postData['change_category_ids']);
        sort($changeCategoryArr);
        $change_category_ids = implode(',', $changeCategoryArr);

        $data = [
            'name' => $postData['name'],
            'change_category_ids' => $change_category_ids,
            'document_str' => $postData['document_str'],
            'status' => $postData['status'],
            'createtime' => time(),
            'updatetime' => time(),
        ];
        Db::startTrans();
        try {
            ChangeFunction::insert($data, true);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }

        return true;
    }

    /**
     * 修改
     * @param $postData
     * @return bool
     */
    public static function updateRow($postData)
    {
        $changeCategoryArr = explode(',', $postData['change_category_ids']);
        sort($changeCategoryArr);
        $change_category_ids = implode(',', $changeCategoryArr);

        $data = [
            'name' => $postData['name'],
            'change_category_ids' => $change_category_ids,
            'document_str' => $postData['document_str'],
            'status' => $postData['status'],
            'updatetime' => time(),
        ];
        Db::startTrans();
        try {
            ChangeFunction::update($data, ['id' => $postData['id']]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }

        return true;
    }

    /**
     * 删除
     * @param $postData
     * @return bool
     */
    public static function deleteRow($postData)
    {
        Db::startTrans();
        try {
            ChangeFunction::where(['id' => $postData['id']])->delete();
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }

        return true;
    }

    public static function getAll()
    {
        $where = '1=1';
        $order = 'a.id desc';
        $field = "a.*";

        $list = db('change_function')
            ->alias('a')
            ->where($where)
            ->order($order)
            ->field($field)
            ->select();
        if (!empty($list)) {
            foreach ($list as &$v) {
                $v['createtimeText'] = isset($v['createtime']) && !empty($v['createtime']) ? date('Y-m-d H:i:s', $v['createtime']) : '';
                $v['statusText'] = isset($v['status']) ? self::getStatusText($v['status']) : '';
                $v['documentStrArr'] = [];
                if (!empty($v['document_str'])) {
                    $v['documentStrArr'] = json_decode($v['document_str'], true);
                    foreach ($v['documentStrArr'] as &$v1) {
                        $v1['template'] = db('template')
                            ->where("id={$v1['id']}")
                            ->field('id, name, src')
                            ->find();
                    }
                    unset($v1);
                }
                $v['changeCategoryArr'] = [];
                if (!empty($v['change_category_ids'])) {
                    $v['changeCategoryArr'] = db('change_category')
                        ->where("id in ({$v['change_category_ids']})")
                        ->field('id, name, status')
                        ->select();
                }
            }
            unset($v);
        }

        return [
            'list' => $list,
        ];

    }

    /**
     * 详情信息
     * @param $where
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getInfo($where)
    {
        $info = db('change_function')
            ->where($where)
            ->find();
        if(!empty($info))
        {
            if (!empty($info['document_str'])) {
                $info['documentStrArr'] = json_decode($info['document_str'], true);
                foreach ($info['documentStrArr'] as &$v) {
                    $v['template'] = db('template')
                        ->where("id={$v['id']}")
                        ->field('id, name, src')
                        ->find();
                }
                unset($v);
            }
        }
        return $info;
    }

}
